#include <iostream>
#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <string>
#include <strings.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstdlib>
#include <pthread.h>
#include "Terminal.hpp"



void Usage(std::string proc)
{
    std::cout<<"\n\rUsage: "<<proc<<" serverip serverport\n"<<std::endl;
}

struct ThreadData
{
    struct sockaddr_in server;
    int sockfd;
};

void* recv_message(void* args)
{
    OpenTerminal();
    ThreadData* td=static_cast<ThreadData*>(args);
    char buffer[1024];
    while(true)
    {
        //发送给服务器后,服务器会回消息
        struct sockaddr_in temp;
        socklen_t len =sizeof(temp);
        ssize_t s = recvfrom(td->sockfd,buffer,sizeof(buffer)-1,0,(sockaddr*)(&temp),&len);
        //recvfrom接受的temp就是服务器,可以不做处理
        if(s)
        {
            buffer[s]=0;
            std::cerr<<buffer<<std::endl;//输出到标准错误
            //配合OpenTerminal,将标准错误输出到终端6
        }
    }
}

void* send_message(void* args)
{
    ThreadData* td=static_cast<ThreadData*>(args);
    std::string message;
    socklen_t len=sizeof(td->server);
    while(true)
    {
        std::cout<<"Please Enter@ ";
        getline(std::cin,message);
        std::cout<<message<<std::endl;
        sendto(td->sockfd,message.c_str(),message.size(),0,(sockaddr*)(&td->server),len);
    }
}

int main(int args, char* argv[])
{
    if(args!=3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip=argv[1];//获取ip
    uint16_t serverport=std::stoi(argv[2]);//获取端口号



    //bind
    //client需要bind,但是由os随机选择,不需要显示bind
    ThreadData td;
    bzero(&td.server,sizeof(td.server));
    td.server.sin_family=AF_INET;
    td.server.sin_port=htons(serverport);
    td.server.sin_addr.s_addr=inet_addr(serverip.c_str());
    //我们想要给服务器发送数据
    //就要构建一个sockaddr server
    //初始化server的信息   family  ip port

    td.sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(td.sockfd<0)
    {
        std::cout<<"socket create error!"<<std::endl;
        return 1;
    }

    pthread_t recvr,sender;
    pthread_create(&recvr,nullptr,recv_message,&td);
    pthread_create(&sender,nullptr,send_message,&td);

    pthread_join(recvr,nullptr);
    pthread_join(sender,nullptr);


    close(td.sockfd);
    return 0;
}